'use strict'

var mongoose = require('mongoose')
var gbook = mongoose.model('gbook')

exports.add = function *(next) {
  try {
    var body = this.request.body;
    var data = new gbook({ userName: body.userName, content: body.content });
    data.save();
    this.body = {
      success: true
    }
  } catch (error) {
    this.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.inquire = function *(next) {
  var page = parseInt(this.query.page) || 1
  var count = parseInt(this.query.count) || 5
  var offset = (page - 1) * count
  var queryArray = [
    gbook
      .find()
      .sort({
        'createAt': -1
      })
      .skip(offset)
      .limit(count)
      .exec(),
      gbook.count().exec()
  ]
  var data = yield queryArray
  this.body = {
    success: true,
    datas: data[0],
    total: data[1]
  }
}
exports.find = function *(next) {
  try {
    var id = this.query._id
    var msg = yield gbook.findById(id)
    msg.success = true
    this.body = msg
  } catch (error) {
    this.body = {
      success: true
    }
  }
}
exports.update = function *(next) {
  try {
    var body = this.request.body;
    var msg = yield gbook.findByIdAndUpdate(body._id, {
      userName: body.userName, content: body.content
    })
    this.body = {
      success: true
    }
  } catch (error) {
    this.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.remove = function *(next) {
  try {
    var id = this.query && this.query._id
    if(id) {
      gbook.findOneAndRemove({_id: id}).exec();
    }
  } catch (error) {
    console.log('删除失败');
  }
  this.body = {
    success: true
  }
}